package one.stand.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.security.MessageDigest;

/**
 * @author: QIK
 * @CreateDate: 2019/6/4 15:50
 * 获取文件md5值
 */
@Slf4j
@Component
public class FileMd5Util {
    /**
     * 文件md5值
     * @param multipartFile
     * @return
     */
    public String getFileMd5Value(MultipartFile multipartFile) {
        try {
            InputStream in = multipartFile.getInputStream();
            byte[] buffer = new byte[2048];
            MessageDigest digest = MessageDigest.getInstance("MD5");
            while (true) {
                int len = in.read(buffer, 0, 2048);
                if (len != -1) {
                    digest.update(buffer, 0, len);
                } else {
                    break;
                }
            }
            in.close();
            byte[] md5Bytes = digest.digest();
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (Exception e) {
            log.error("获取文件md5失败");
        }
        return null;
    }

}
